"""
部门管理接口
作者：资深Flask讲师
功能：部门列表、部门详情、部门创建、部门更新等
权限：超级管理员可操作所有部门，部门经理可查看本部门信息
"""

from flask import Blueprint, jsonify, request
from myflask.tools.bd import db
from myflask.models.department import Department
from myflask.models.user import User
from myflask.tools.auth import require_role

department_blue = Blueprint('department_blue', __name__)


@department_blue.route('/list', methods=['GET'])
def department_list():
    """
    获取部门列表
    权限：所有登录用户可查看
    """
    try:
        user_info = getattr(request, 'user_info', None)
        
        # 查询所有部门
        departments = Department.query.filter_by(status=1).order_by(Department.created_at.desc()).all()
        
        return jsonify({
            "code": 200,
            "message": "获取部门列表成功",
            "data": {
                "departments": [dept.to_dict(include_users=False) for dept in departments],
                "total": len(departments)
            }
        })
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取部门列表失败: {str(e)}"
        }), 500


@department_blue.route('/detail/<int:dept_id>', methods=['GET'])
def department_detail(dept_id):
    """
    获取部门详情（包含部门员工列表）
    权限：超级管理员可查看所有部门，部门经理和员工只能查看本部门
    """
    try:
        user_info = getattr(request, 'user_info', None)
        
        # 查询部门
        department = Department.query.get(dept_id)
        
        if not department:
            return jsonify({
                "code": 404,
                "message": "部门不存在"
            }), 404
        
        # 权限检查
        if user_info.get('role') != 'admin':
            # 非管理员只能查看本部门
            if user_info.get('department_id') != dept_id:
                return jsonify({
                    "code": 403,
                    "message": "权限不足：只能查看本部门信息"
                }), 403
        
        return jsonify({
            "code": 200,
            "message": "获取部门详情成功",
            "data": department.to_dict(include_users=True)
        })
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取部门详情失败: {str(e)}"
        }), 500


@department_blue.route('/create', methods=['POST'])
@require_role('admin')
def department_create():
    """
    创建部门
    权限：仅超级管理员
    请求体：{"name": "技术部", "description": "负责技术研发", "manager_id": 2}
    """
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({
                "code": 400,
                "message": "请求数据格式错误"
            }), 400
        
        name = data.get('name', '').strip()
        description = data.get('description', '').strip()
        manager_id = data.get('manager_id')
        
        # 数据验证
        if not name:
            return jsonify({
                "code": 400,
                "message": "部门名称不能为空"
            }), 400
        
        # 检查部门名称是否已存在
        existing_dept = Department.query.filter_by(name=name).first()
        if existing_dept:
            return jsonify({
                "code": 400,
                "message": "部门名称已存在"
            }), 400
        
        # 如果指定了经理，验证经理是否存在
        if manager_id:
            manager = User.query.get(manager_id)
            if not manager:
                return jsonify({
                    "code": 400,
                    "message": "指定的经理不存在"
                }), 400
        
        # 创建新部门
        new_department = Department(
            name=name,
            description=description if description else None,
            manager_id=manager_id if manager_id else None,
            status=1
        )
        
        db.session.add(new_department)
        db.session.commit()
        
        # 如果指定了经理，更新经理角色
        if manager_id:
            manager = User.query.get(manager_id)
            manager.role = 'manager'
            manager.department_id = new_department.id
            db.session.commit()
        
        return jsonify({
            "code": 200,
            "message": "创建部门成功",
            "data": new_department.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "code": 500,
            "message": f"创建部门失败: {str(e)}"
        }), 500


@department_blue.route('/update/<int:dept_id>', methods=['PUT'])
@require_role('admin')
def department_update(dept_id):
    """
    更新部门信息
    权限：仅超级管理员
    请求体：{"name": "技术部", "description": "负责技术研发", "manager_id": 2}
    """
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({
                "code": 400,
                "message": "请求数据格式错误"
            }), 400
        
        # 查询部门
        department = Department.query.get(dept_id)
        
        if not department:
            return jsonify({
                "code": 404,
                "message": "部门不存在"
            }), 404
        
        # 更新字段
        if 'name' in data:
            # 检查名称是否重复
            existing_dept = Department.query.filter(
                Department.name == data['name'],
                Department.id != dept_id
            ).first()
            if existing_dept:
                return jsonify({
                    "code": 400,
                    "message": "部门名称已存在"
                }), 400
            department.name = data['name']
        
        if 'description' in data:
            department.description = data['description']
        
        if 'manager_id' in data:
            old_manager_id = department.manager_id
            new_manager_id = data['manager_id']
            
            # 如果更换经理
            if old_manager_id != new_manager_id:
                # 取消旧经理的经理角色
                if old_manager_id:
                    old_manager = User.query.get(old_manager_id)
                    if old_manager:
                        old_manager.role = 'employee'
                
                # 设置新经理
                if new_manager_id:
                    new_manager = User.query.get(new_manager_id)
                    if not new_manager:
                        return jsonify({
                            "code": 400,
                            "message": "指定的经理不存在"
                        }), 400
                    new_manager.role = 'manager'
                    new_manager.department_id = dept_id
                
                department.manager_id = new_manager_id
        
        db.session.commit()
        
        return jsonify({
            "code": 200,
            "message": "更新部门信息成功",
            "data": department.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "code": 500,
            "message": f"更新部门信息失败: {str(e)}"
        }), 500


@department_blue.route('/delete/<int:dept_id>', methods=['DELETE'])
@require_role('admin')
def department_delete(dept_id):
    """
    删除部门（软删除，设置status=0）
    权限：仅超级管理员
    """
    try:
        # 查询部门
        department = Department.query.get(dept_id)
        
        if not department:
            return jsonify({
                "code": 404,
                "message": "部门不存在"
            }), 404
        
        # 检查部门下是否有员工
        employees_count = User.query.filter_by(department_id=dept_id).count()
        if employees_count > 0:
            return jsonify({
                "code": 400,
                "message": f"部门下还有{employees_count}名员工，无法删除"
            }), 400
        
        # 软删除
        department.status = 0
        db.session.commit()
        
        return jsonify({
            "code": 200,
            "message": "删除部门成功"
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "code": 500,
            "message": f"删除部门失败: {str(e)}"
        }), 500

